<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>哈哈</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .box {
            width: 350px;
            height: 350px;
            margin: 100px;
            border: 1px solid #ccc;
            position: relative;
        }

        .big {
            width: 400px;
            height: 400px;
            position: absolute;
            top: 0;
            left: 360px;
            border: 1px solid #ccc;
            overflow: hidden;
            display: none;
        }

        .mask {
            width: 175px;
            height: 175px;
            background: rgba(255, 255, 0, 0.4);
            position: absolute;
            top: 0px;
            left: 0px;
            cursor: move;
            display: none;
        }

        .small {
            position: relative;
        }
    </style>
</head>
<body>
<div class="box" id="box">
    <div class="small"><!--小层-->
        <img src="images/small.png" width="350" alt=""/>
        <div class="mask"></div><!--遮挡层-->
    </div><!--小图-->
    <div class="big"><!--大层-->
        <img src="images/big.jpg" width="800" alt=""/><!--大图-->
    </div><!--大图-->
</div>
<script>
    function getById(id) {
        return document.getElementById(id);
    }

    var boxObj = getById('box');
    var smallObj = boxObj.children[0];
    var maskObj = smallObj.children[1];
    var bigObj = boxObj.children[1];
    var bigImg = bigObj.children[0];
    boxObj.onmouseover = function () {
        maskObj.style.display = "block";
        bigObj.style.display = "block";
    };
    boxObj.onmouseout = function () {
        maskObj.style.display = "none";
        bigObj.style.display = "none";
    };
    smallObj.onmousemove = function (e) {
        var x = e.clientX - maskObj.offsetWidth / 2 - 100;
        var y = e.clientY - maskObj.offsetHeight / 2 - 100;
        x = x < 0 ? 0 : x;
        y = y < 0 ? 0 : y;
        var maxX = smallObj.offsetWidth - maskObj.offsetWidth;
        var maxY = smallObj.offsetHeight - maskObj.offsetHeight;
        x = x > maxX ? maxX : x;
        y = y > maxY ? maxY : y;
        //console.log([x,y]);
        //mask的位置
        maskObj.style.left = x + "px";
        maskObj.style.top = y + "px";
        //大图的位置
        var bigX = bigImg.offsetWidth - bigObj.offsetWidth;
        var bigY = bigImg.offsetHeight - bigObj.offsetHeight;
        var bigImgX = x * bigX / (smallObj.offsetWidth - maskObj.offsetWidth);
        var bigImgY = y * bigY / (smallObj.offsetHeight - maskObj.offsetHeight);
        bigImg.style.marginLeft = -bigImgX + "px";
        bigImg.style.marginTop = -bigImgY + "px";
    }

</script>


</body>
</html>
